package hc

import (
	"fmt"
	"net"
)

// 变量
var (
	ServiceName = "rpc" // 服务名
	LogDir      = "."   // 日志路径
	Debug       = false // 调试模式
	// registerError error
)

// ListenAndServe 启动服务
func ListenAndServe(address string, port int) error {
	InitLog()
	go registerServer("jsonrpc", address, port)
	serviceAddress := fmt.Sprintf("%s:%d", address, port)
	addr, _ := net.ResolveTCPAddr("tcp", serviceAddress)
	l, err := net.ListenTCP("tcp", addr)
	if err != nil {
		return err
	}
	for {
		conn, err := l.Accept()
		if err != nil {
			continue
		}
		go ServeConn(conn)
	}
}

// ListenAndJSONServe 启动jsonrpc服务
func ListenAndJSONServe(address string, port int) error {
	InitLog()
	go registerServer("jsonrpc", address, port)
	serviceAddress := fmt.Sprintf("%d", port)
	addr, _ := net.ResolveTCPAddr("tcp", serviceAddress)
	l, err := net.ListenTCP("tcp", addr)
	if err != nil {
		return err
	}
	fmt.Print("注册并启动rpc服务成功!\n")
	fmt.Print("----------------------\n")
	fmt.Printf("服务: %s\n", ServiceName)
	fmt.Printf("地址: %s:%d\n", address, port)
	fmt.Print("----------------------\n")
	for {
		conn, err := l.Accept()
		if err != nil {
			continue
		}
		// go hc.ServeConn(conn)
		go JSONServeConn(conn)
	}
}
